<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="isCreator"
          v-hasPermi="['element:file:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList">
      <el-table-column
        label="文件名称"
        align="center"
        prop="originalFileName"
      />
      <el-table-column label="文件类型" align="center" prop="fileType">
        <template #default="{ row }">{{
          row.fileType === 1 ? "网络外链" : "系统文件"
        }}</template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize" />

      <el-table-column label="文件路径" align="center" prop="url" />
      <el-table-column label="文件用途描述" align="center" prop="fileDesc" />
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        width="100"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <span v-if="row.status === -1">未审核</span>
          <span v-else-if="row.status === -2">已驳回</span>
          <template v-else>
            <el-switch
              :value="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="toggleStatus(row)"
            ></el-switch>
            <span>{{ row.status ? "上架" : "下架" }}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            v-if="isCreator"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['element:file:edit']"
            >修改</el-button
          >
          <el-button
            v-if="canDownload(scope.row)"
            size="mini"
            type="text"
            @click="handleDownload(scope.row)"
            >下载</el-button
          >
          <el-button
            v-if="isCreator"
            size="mini"
            type="text"
            style="color: red"
            @click="handleDelete(scope.row)"
            v-hasPermi="['element:file:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改元素信息-模型、数据集对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="文件类型" prop="fileType">
          <el-radio-group v-model="form.fileType" @change="typeChange">
            <el-radio :label="1">网络外链</el-radio>
            <el-radio :label="2">系统文件</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.fileType === 2">
          <el-form-item class="file-form-item">
            <ShardUpload
              v-model="form.url"
              :limit="1"
              :fileSize="2200"
              :fileType="false"
              :nameList="[form.attachFileName]"
              @uploadSuccess="uploadSuccess"
            />
          </el-form-item>
        </template>
        <el-form-item label="文件名称" prop="originalFileName">
          <el-input
            v-model="form.originalFileName"
            placeholder="请输入文件名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="文件大小" prop="fileSize">
          <el-input
            v-model="form.fileSize"
            :readonly="form.fileType === 2"
            placeholder="请输入文件大小"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件路径" prop="url">
          <el-input
            v-model="form.url"
            :readonly="form.fileType === 2"
            placeholder="请输入文件路径"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件用途描述" prop="fileDesc">
          <el-input
            v-model="form.fileDesc"
            placeholder="请输入文件用途描述"
            :maxlength="100"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveAs } from "file-saver";
import { Loading } from "element-ui";
import {
  getFileList,
  addFile,
  editFile,
  removeFile,
  getFileDetail,
  toggleFileStatus,
} from "@/api/element/elementProvide";
import { transformSize } from "@/utils";
import request from "@/utils/request";
import ShardUpload from "@/components/FileUpload/shardUpload.vue";

export default {
  name: "ElementProvideFile",
  components: { ShardUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 元素信息-模型、数据集表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        elementProvideId: this.$route.query.id,
      },
      // 表单参数
      form: {
        elementProvideId: this.$route.query.id,
        url: "",
        fileSize: "",
        originalFileName: "",
        fileType: null,
      },
      // 表单校验
      rules: {
        originalFileName: [{ required: true, message: "文件名称不能为空" }],
        fileType: [{ required: true, message: "文件类型不能为空" }],
        url: [{ required: true, message: "文件路径不能为空" }],
        fileSize: [{ required: true, message: "文件大小不能为空" }],
      },
    };
  },
  computed: {
    isCreator() {
      return (
        this.$store.state.user.id ===
        Number(localStorage.getItem("elementProvideCreateUserId"))
      );
    },
    canDownload() {
      return (row) => {
        if (row.status === 1) {
          return true;
        } else if (this.isCreator) {
          return true;
        }
        return false;
      };
    },
  },
  created() {
    this.getList();
  },
  methods: {
    async handleDownload(row) {
      if (row.url.startsWith("https://laoxiang-plate.oss")) {
        window.open(row.url);
      } else {
        const downloadLoadingInstance = Loading.service({
          text: "正在下载数据，请稍候",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        try {
          const stream = await request({
            url: row.url,
            method: "get",
            responseType: "blob",
          });
          const suffix = stream.type.split("/")[1];
          const fileName = row.originalFileName.endsWith(suffix)
            ? row.originalFileName
            : `${row.originalFileName}.${suffix}`;
          saveAs(stream, fileName);
        } finally {
          downloadLoadingInstance.close();
        }
      }
    },
    async toggleStatus(row) {
      const { id, status } = row;
      const { code } = await toggleFileStatus({
        id,
        status: Number(!status),
      });
      if (code === 200) {
        this.$message.success(status ? "下架成功" : "上架成功");
        this.$set(row, "status", Number(!status));
      }
    },
    typeChange() {
      this.$set(this.form, "url", "");
      this.$set(this.form, "fileSize", "");
      this.$nextTick(() => {
        this.$refs.form.clearValidate(["url", "fileSize"]);
      });
    },
    uploadSuccess({ fileSize, url, name }) {
      this.form.fileSize = transformSize(fileSize);
      this.form.originalFileName = name;
    },
    /** 查询元素信息-模型、数据集列表 */
    getList() {
      this.loading = true;
      getFileList(this.queryParams).then((response) => {
        this.fileList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        elementProvideId: this.$route.query.id,
        url: "",
        fileSize: "",
        originalFileName: "",
        fileType: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getFileDetail(id).then((response) => {
        this.form = response.data;

        this.open = true;
        this.title = "修改文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.form.elementDomain = this.form.elementDomain.join(",");
          // this.form.elementTag = this.form.elementTag.join(",");
          if (this.form.id != null) {
            editFile(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(
          '是否确认删除元素信息-模型、数据集编号为"' + ids + '"的数据项？'
        )
        .then(function () {
          return removeFile({ ids });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "element/elementProvide/export",
        {
          ...this.queryParams,
        },
        `elementProvide_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
